var express = require('express');
var router = express.Router();
var { adminModel, routerModel, studentModel, questionModel, paperModel, academyModel, clazzModel, stageModel, resultModel } = require('../model/model')

router.post('/back_login', async (req, res) => {
    let { name, password } = req.body
    let result = await adminModel.find({ $and: [{ name }, { password }] })
    if (result.length > 0) {
        if (result[0].status) {
            res.send({
                code: 201,
                mess: '登陆成功',
                uid: result[0]._id,
                uname: result[0].name
            })
        }
    } else {
        res.send({
            code: 404,
        })
    }
})

router.post('/send_code', async (req, res) => {
    let { phone, content } = req.body
    const tencentcloud = require("tencentcloud-sdk-nodejs-sms");
    const SmsClient = tencentcloud.sms.v20210111.Client;

    // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
    const clientConfig = {
        credential: {
            secretId: "AKIDQvWNSXvHXyV9pPFKSZSIGD5sklqtvmVH",
            secretKey: "sdQQciHxihFgF9wfIpbLE6FXuVtBMSZZ",
        },
        region: "ap-beijing",
        profile: {
            httpProfile: {
                endpoint: "sms.tencentcloudapi.com",
            },
        },
    };

    // 实例化要请求产品的client对象,clientProfile是可选的
    const client = new SmsClient(clientConfig);
    const params = {
        PhoneNumberSet: [phone],
        SmsSdkAppId: "1400925850",
        TemplateId: "2220323",
        SignName: "夕昔果冻公众号",
        TemplateParamSet: [content]
    };
    let result = await client.SendSms(params)
    if (result.SendStatusSet[0].Code === 'Ok') {
        res.send({
            code: 200,
            mess: '发送成功'
        })
    } else {
        res.send({
            code: 404,
            mess: '发送失败'
        })
    }
})

router.post('/mess_login', async (req, res) => {
    let { phone } = req.body
    let result = await adminModel.find({ phone })
    if (result.length > 0) {
        if (result[0].status) {
            res.send({
                code: 201,
                uid: result[0]._id,
                uname: result[0].name
            })
        }
    } else {
        res.send({
            code: 404,
            uid: '',
            uname: ''
        })
    }
})

router.post('/reset_send', async (req, res) => {
    let { phone, content } = req.body
    const tencentcloud = require("tencentcloud-sdk-nodejs-sms");
    const SmsClient = tencentcloud.sms.v20210111.Client;

    const clientConfig = {
        credential: {
            secretId: "AKIDQvWNSXvHXyV9pPFKSZSIGD5sklqtvmVH",
            secretKey: "sdQQciHxihFgF9wfIpbLE6FXuVtBMSZZ",
        },
        region: "ap-beijing",
        profile: {
            httpProfile: {
                endpoint: "sms.tencentcloudapi.com",
            },
        },
    };

    // 实例化要请求产品的client对象,clientProfile是可选的
    const client = new SmsClient(clientConfig);
    const params = {
        PhoneNumberSet: [phone],
        SmsSdkAppId: "1400925850",
        TemplateId: "2236320",
        SignName: "夕昔果冻公众号",
        TemplateParamSet: [content]
    };
    let result = await client.SendSms(params)
    if (result.SendStatusSet[0].Code === 'Ok') {
        res.send({
            code: 200,
            mess: '发送成功'
        })
    } else {
        res.send({
            code: 404,
            mess: '发送失败'
        })
    }
})

router.post('/resetcode', async (req, res) => {
    let { phone, password } = req.body
    let result = await adminModel.find({ phone })
    if (result.length > 0) {
        result[0].password = password
        let aa = await adminModel.updateOne({ _id: result[0]._id },result[0])
        console.log(aa);
        res.send({
            code: 201,
            mess: '更改密码成功, 即将跳转至登录界面'
        })
    } else {
        res.send({
            code: 404,
            mess: '手机号出错, 请检查后重试'
        })
    }
})

router.get('/get_home', async (req, res) => {
    let { uid } = req.query
    let role = await adminModel.find({ _id: uid })
    if (role.length > 0) {
        if (role[0].role === '超级管理员') {
            let menu = await routerModel.find().lean()
            let menu1 = []
            menu.forEach(ele => {
                if (!ele.pid) {
                    menu1.push({
                        key: ele.url,
                        label: ele.name,
                        _id: ele._id
                    })
                } else {
                    menu1.push({
                        key: ele.url,
                        label: ele.name,
                        pid: ele.pid,
                        _id: ele._id
                    })
                }
            })

            let obj = {}
            menu1.forEach(item => {
                obj[item._id] = item
            })

            let list = []
            menu1.forEach(el => {
                if (!el['pid']) {
                    list.push(obj[el._id])
                } else {
                    if (!obj[el['pid']]['children']) {
                        obj[el['pid']]['children'] = []
                    }
                    obj[el['pid']]['children'].push(el)
                }
            })

            res.send({
                code: 200,
                list
            })
        } else {
            let menu = await routerModel.find().lean()
            let obj = {}
            let menu1 = []
            menu.forEach(ele => {
                if (!ele.pid) {
                    menu1.push({
                        key: ele.url,
                        label: ele.name,
                        _id: ele._id
                    })
                } else {
                    menu1.push({
                        key: ele.url,
                        label: ele.name,
                        pid: ele.pid,
                        _id: ele._id
                    })
                }
            })

            menu1.forEach(item => {
                obj[item._id] = item
            })

            let list = []
            menu1.forEach(el => {
                if (!el.pid) {
                    if (String(el.key) === '/home/working') {
                        list.push(obj[el._id])
                    }
                }
            })

            res.send({
                code: 200,
                list
            })
        }
    }

})

router.post('/examlogin', async (req, res) => {
    let { name, card, tid } = req.body
    let result = await studentModel.find({ $and: [{ name }, { card }, { tid }] })
    if (result.length > 0) {
        res.send({
            code: 201,
            sid: result[0]._id
        })
    } else {
        res.send({
            code: 404,
            sid: ''
        })
    }
})

router.get('/get_data', async (req, res) => {
    let data = await questionModel.find({ status: 0 })
    let data1 = await paperModel.find({ flag: 1 })
    let clazz = await clazzModel.find()
    let stage = await stageModel.find()
    let academy = await academyModel.find()
    let user = await adminModel.findOne({_id:req.query.uid})
    console.log(user.role,'role');
    res.send({
        code: 200,
        question: data.length,
        paper: data1.length,
        clazz,
        academy,
        stage,
        role:user.role
    })
})

router.post('/chartsdata', async (req, res) => {
    let { classid } = req.body
    let result = await resultModel.find({ clazz: classid }).populate(['student', 'paper', 'clazz'])

    let namelist = []
    let testname = []
    let series = []
    result.forEach(item => {
        if (namelist.indexOf(item.student.name) === -1) {
            namelist.push(item.student.name)
        }
        if (testname.indexOf(item.paper.name) === -1) {
            testname.push(item.paper.name)
        }
        series.push({
            name: item.student.name,
            type: 'line',
            stack: 'Total',
            data: [],
        })
    })

    result.forEach(item => {
        series.forEach(el => {
            testname.forEach(e => {
                if (el.name === item.student.name) {
                    if (item.paper.name === e) {
                        el.data.push(item.grade)
                    }
                }
            })
        })
    })
    function uniqueByKey(array, key) {
        return array.filter((obj, index) =>
            index === array.findIndex((obj2) => obj2[key] === obj[key])
        );
    }
    const series1 = uniqueByKey(series, 'name');

    res.send({
        code: 200,
        namelist,
        testname,
        series1
    })
})

router.post('/ckrole', async (req, res) => {
    let { uid } = req.body
    let result = await adminModel.find({ _id: uid })
    res.send({
        code: 200,
        urole: result[0].role
    })
})
module.exports = router;